package com.sskj.b70.m.http;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.m.HttpConfig;
import com.sskj.b70.m.bean.HttpData;
import com.sskj.b70.utils.GSonUtil;
import com.sskj.b70.utils.ToastUtil;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import okhttp3.ResponseBody;

/**
 * Created by lvzhihao on 17-7-4.
 */

public abstract class JsonConverter<T> extends AbsConverter<T> {

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        T data;
        try {
            String jsonBody = body.string();
            jsonBody = jsonBody.replace("\"data\":\"\"}", "\"data\":null}");
            Gson gson = GSonUtil.gson;
            Type genericSuperclass = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            data = gson.fromJson(jsonBody, type);
        } catch (IOException e) {
            throw new JsonParseException();
        } catch (JsonSyntaxException e) {
            throw new JsonParseException();
        }
        int status;
        String msg;
        if (data instanceof HttpData) {
            status = ((HttpData) data).getStatus();
            msg = ((HttpData) data).getMsg();
        } else if (data instanceof Map) {
            Map<String, String> map = (Map<String, String>) data;
            status = Integer.valueOf(map.get("status"));
            msg = map.get("msg");
        } else {
            status = -1;
            msg = "";
        }
        if (status == HttpConfig.ACCOUNT_NO_EXIST) {//账户不存在
            ToastUtil.showShort(msg);
            MyAppLication.getApplication().logout();
            throw new ToastException(msg);
        } else if (status == HttpConfig.STATUS_OK) {
            return data;
        } else {
            throw new ToastException(msg);
        }
    }

}
